package org.geektimes.http.server.jdk.servlet;

import java.util.Collection;
import java.util.List;
import java.util.ServiceLoader;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * 组合url pattern matcher {@link URLPatternsMatcher}.
 * <br> @author leo
 * <br> @date 2021/7/1
 * <br> @since 1.0.0
 */
public class CompositeUrlPatternsMatcher implements URLPatternsMatcher {
    private final List<URLPatternsMatcher> urlPatternsMatcherList;

    public CompositeUrlPatternsMatcher() {
        this(Thread.currentThread().getContextClassLoader());
    }

    public CompositeUrlPatternsMatcher(ClassLoader classLoader) {
        urlPatternsMatcherList = loadUrlPatternsMather(classLoader);
    }

    /**
     * SPI load url pattern.
     * {@link ServiceLoader#load(Class, ClassLoader)}
     * path "/META-INF/services/org.geektimes.http.server.jdk.URLPatternsMatcher"
     * @param classLoader
     * @return
     */
    private List<URLPatternsMatcher> loadUrlPatternsMather(ClassLoader classLoader) {
        //根据URLPatternsMatcher#getOrder 排序
        return StreamSupport.stream(ServiceLoader.load(URLPatternsMatcher.class,classLoader).spliterator(), false)
                .sorted(PRIORITY_COMPARATOR).collect(Collectors.toList());
    }

    @Override
    public boolean matches(Collection<String> urlPatterns, String requestURI) {
        for (URLPatternsMatcher matcher : urlPatternsMatcherList) {
            if (matcher.matches(urlPatterns,requestURI)){
                return true;
            }
        }
        return false;
    }
}
